package cn.edu.lingnan.servlet;

import cn.edu.lingnan.pojo.Student;
import cn.edu.lingnan.service.IStudentService;
import cn.edu.lingnan.service.StudentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("GBK");
//        resp.setCharacterEncoding("GBK");

        //1 从页面中获取表单中提交的数据，使用getParameter()方法，建议参数名与数据库一致
        int id = Integer.parseInt(req.getParameter("id"));
        String password = req.getParameter("password");
        //建议使用输出语句输出读取参数的结果，不仅仅是看读到内容了，还要看是否有中文乱码
        System.out.println("[Debug] id and password value is "+id+"  "+password);
        //2 调用业务逻辑，一种是调用service中类的方法,另一种是其他，比如注销
        StudentService service = new IStudentService();
        Student student = service.studentLogin(id,password);
        HttpSession session = req.getSession();
        session.setAttribute("right",student.getRight());//一定要有set才有get
        session.setAttribute("sid",student.getId());//学生报名时需要用到的参数
        if (student.getRight()==1) {
            session.setAttribute("sright","管理员");
        }else {
            session.setAttribute("sright","游客");
        }

        //3 依据返回结果，返回到相应的用户页面
        if(student.getId()>0){
            resp.sendRedirect("/main.jsp");
        }else {
            resp.sendRedirect("/loginError.html");
        }


    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
